# Multi-stage build for Spring Boot Application

# Stage 1: Build
FROM maven:3.8-openjdk-17-slim AS build
WORKDIR /app

# Copy pom.xml and download dependencies
COPY pom.xml .
RUN mvn dependency:go-offline -B

# Copy source code and build
COPY src ./src
RUN mvn clean package -DskipTests

# Stage 2: Runtime
FROM openjdk:17-jdk-slim
WORKDIR /app

# Create user for running the application
RUN groupadd -r spring && useradd -r -g spring spring

# Copy the JAR file from build stage
COPY --from=build /app/target/springboot-apm-demo.jar app.jar

# Copy SkyWalking agent (if exists)
# Uncomment if you want to include agent in the image
# COPY skywalking-agent /app/skywalking-agent

# Set environment variables
ENV JAVA_OPTS="-Xms512m -Xmx1024m" \
    SKYWALKING_BACKEND="10.10.10.125:11800" \
    SERVICE_NAME="springboot-apm-demo"

# Change ownership
RUN chown -R spring:spring /app

# Switch to non-root user
USER spring

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
  CMD curl -f http://localhost:8080/actuator/health || exit 1

# Run without SkyWalking agent
ENTRYPOINT ["sh", "-c", "java ${JAVA_OPTS} -jar app.jar"]

# To run with SkyWalking agent, use:
# ENTRYPOINT ["sh", "-c", "java ${JAVA_OPTS} -javaagent:skywalking-agent/skywalking-agent.jar -Dskywalking.agent.service_name=${SERVICE_NAME} -Dskywalking.collector.backend_service=${SKYWALKING_BACKEND} -jar app.jar"]

